package com.vm.fragment;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.vm.adapter.GoodsGridAdapter;
import com.vm.commons.VMConst;
import com.vm.model.Goods;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

@SuppressLint("InflateParams")
public class MallFragment extends BaseFragment {
	protected static final String TAG = "PopularOnlineActivity";

	private RequestQueue mQueue;
	private View view;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("MallFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.mall1, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		isPrepared = true;
		lazyLoad();
		view.setVisibility(View.INVISIBLE);
		return view;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	protected void lazyLoad() {
		Log.i("MallFragment", "lazyLoad");
		Log.i("lazyLoad", "isPrepared=" + isPrepared + ",isVisible="
				+ isVisible + ",mHasLoadedOnce=" + mHasLoadedOnce);
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		Log.i("MallFragment", "lazyLoad--AsyncTask");
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
				// final WarningDialog dialog = new
				// WarningDialog(getActivity());
				// dialog.show();
				// dialog.setClicklistener(new
				// WarningDialog.ClickListenerInterface() {
				//
				// @Override
				// public void doConfirm() {
				// // TODO Auto-generated method stub
				// dialog.dismiss();
				// }
				// });
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(2000);
					// 在这里添加调用接口获取数据的代码
					// doSomething()
					initData();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					// setView();
					mHasLoadedOnce = true;
				} else {
					
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
				
				view.setVisibility(View.VISIBLE);
			}
		}.execute();

	}

	public void initData() {
		mQueue = MyVolley.getRequestQueue();
		String url = VMConst.REQUEST_URL + "getAllGoods";

		JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						// arg0.length();
						List<Goods> list_goods = new ArrayList<Goods>();
						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								Goods goods = JsonUtils.jsonToBean(jsonObject,
										Goods.class);
								if (goods != null) {
									list_goods.add(goods);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						GoodsGridAdapter myAdapter = new GoodsGridAdapter(
								getActivity(), list_goods);
						GridView gridview = (GridView) getActivity()
								.findViewById(R.id.gv_book);
						gridview.setAdapter(myAdapter);
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}
}
